#pragma once

#include <iostream>
#include <string>
#include "LockGuard.hpp"
#include "Log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include "InetAddr.hpp"
#include <unistd.h>
#include <sys/wait.h>
#include <functional>
#include <pthread.h>

#include "Socket.hpp" //以后创建，绑定套接字什么的都在这里面了，包头文件用即可
#include <memory>

using namespace socket_ns; // 展开命名空间

class TcpServer; // 前置声明

using http_t = std::function<std::string(std::string &reqeust)>;

class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr addr, TcpServer *s)
        : sockfd(fd), clientaddr(addr), self(s)
    {
    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port, http_t service)
        : _localaddr("0", port), _listensockfd(std::make_unique<TcpSocket>()), _isrunning(false), _http_service(service)
    {
        _listensockfd->BuildListenSocket(_localaddr); // 构造服务器，一步就创建套接字bind，listen什么全做好了封装的效果
    }
    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        std::string request, response;

        // 有较大的概率，读到的就是一个完整的http request
        ssize_t n = td->sockfd->Recv(&request); // 读取请求
        if (n > 0)
        {
            response = td->self->_http_service(request);
            td->sockfd->Send(response); // 发送应答
        }
        td->sockfd->Close(); // 关闭文件描述符
        delete td;
        return nullptr;
    }
    // 启动
    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 4. 不能直接接受数据，先获取连接
            InetAddr peeraddr;
            socket_sptr normalsock = _listensockfd->Accepter(&peeraddr);
            // 连接成功的话，就分配一个新的sockfd
            if (normalsock == nullptr)
                continue;
            // version 2: 采用多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(normalsock, peeraddr, this); // 每个线程客户端都要配一份，堆开辟
            pthread_create(&tid, nullptr, HandlerSock, td);              // 线程分离，不用管回收
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    InetAddr _localaddr;
    std::unique_ptr<Socket> _listensockfd;
    bool _isrunning;
    http_t _http_service;
};
